#!/bin/bash

# 定义默认启动模式及路径
SERVER="all"
WEB_CHAT_START_PAGE_JARS="./server"
KILL_TIMEOUT=5  # 等待进程退出的最长时间（秒）

# 参数处理（支持带.jar后缀和不带的情况）
if [ $# -gt 0 ]; then
  SERVER="${1%.*}" # 去除可能的.jar后缀
fi

echo "Starting server: $SERVER"

# 打包阶段
echo "=== Webchat packaging begins ==="
mvn clean package -DskipTests=true
echo "=== Webchat packaging completed ==="

# 清理并创建jars目录
rm -rf "$WEB_CHAT_START_PAGE_JARS"
mkdir -p "$WEB_CHAT_START_PAGE_JARS"
echo "Old jars removed"

# 复制所有jar到目标目录
find . -path "*/target/*.jar" -exec cp {} "$WEB_CHAT_START_PAGE_JARS" \;

cd "$WEB_CHAT_START_PAGE_JARS" || exit 1

# 定义进程终止函数
kill_old_process() {
  local jar_name=$1
  local pid_list=$(pgrep -f "java.*$jar_name")

  if [ -n "$pid_list" ]; then
    echo "Found existing process(es) for $jar_name: $pid_list"

    # 优雅终止
    kill $pid_list
    echo "Sent SIGTERM to process(es), waiting for termination..."

    # 等待进程退出
    local timeout=0
    while kill -0 $pid_list 2>/dev/null && [ $timeout -lt $KILL_TIMEOUT ]; do
      sleep 1
      ((timeout++))
    done

    # 强制终止未退出的进程
    if kill -0 $pid_list 2>/dev/null; then
      echo "Force killing process(es)..."
      kill -9 $pid_list
    fi

    # 二次确认
    if pgrep -f "java.*$jar_name" >/dev/null; then
      echo "Error: Failed to kill process for $jar_name!" >&2
      return 1
    fi
  fi
  return 0
}

# 启动逻辑
if [ "$SERVER" == "all" ]; then
  echo "Starting ALL services..."
  for jar in *.jar; do
    service_name="${jar%.*}"

    # 终止旧进程
    if ! kill_old_process "$jar"; then
      exit 1
    fi

    # 启动新进程
    echo "Starting $service_name..."
    nohup java -jar "$jar" > "${service_name}.log" 2>&1 &
  done
  echo "All services restarted in background."
else
  target_jar="${SERVER}.jar"
  if [ -f "$target_jar" ]; then
    # 终止旧进程
    if ! kill_old_process "$target_jar"; then
      exit 1
    fi

    # 启动新进程
    echo "Starting $target_jar..."
    nohup java -jar "$target_jar" > "${SERVER}.log" 2>&1 &
    echo "Service restarted. Tracking logs:"
    tail -100f "${SERVER}.log"
  else
    echo "Error: Jar file $target_jar not found!"
    echo "Available jars:"
    ls -1 *.jar | sed 's/.jar$//'
    exit 1
  fi
fi

# 端口冲突检查（备用方案）
check_port_conflict() {
  local port=$1
  if lsof -i :$port &>/dev/null; then
    echo "Port $port is still in use after process restart!" >&2
    return 1
  fi
  return 0
}